<template>
<div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
        <el-form :inline="true" :model="filters" :size="size">
            <el-row class="search-input">
                <el-form-item label="属性名称：">
                    <el-input v-model="filters.name" clearable placeholder="属性名称" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="属性编码：">
                    <el-input v-model="filters.code" clearable placeholder="属性编码" style="width: 200px;"></el-input>
                </el-form-item>
            </el-row>
            <el-row class="search-button">
                <el-form-item>
                    <kt-button icon="fa fa-search" :label="$t('action.search')" type="primary" @click="findPage(null)" />
                </el-form-item>
                <el-form-item>
                    <kt-button icon="fa fa-plus" :label="$t('action.add')" type="primary" @click="handleAdd" />
                </el-form-item>
                <el-form-item>
                    <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetForm('filters')" />
                </el-form-item>
            </el-row>
            <!--表格显示列界面-->
            <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns" @handleFilterColumns="handleFilterColumns"></table-column-filter-dialog>
        </el-form>
    </div>
    <!--表格内容栏-->
    <cy-table :height="350" :highlightCurrentRow="true" :content="pageResult" :totalSize="totalSize" :columns="filterColumns" @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete" ref="CyTable"></cy-table>
    <!--新增编辑界面-->
    <el-dialog :title="operation ? '新增' : '编辑'" width="50%" :visible.sync="dialogVisible" :close-on-click-modal="false">
        <el-form :model="dataForm" label-width="200px" ref="dataForm" :size="size" label-position="right" :rules="dataFormRules">
            <el-form-item label="ID" prop="id" v-if="false">
                <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
            </el-form-item>
            <el-table :data="tableData" style=" width:542px;">
                <el-table-column prop="code" label="属性编码" width="180">
                    <template slot-scope="scope">
                        <el-input v-model="dataForm.code" auto-complete="off"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="属性名称" width="180">
                    <template slot-scope="scope">
                        <el-input v-model="dataForm.name" auto-complete="off"></el-input>
                    </template>
                </el-table-column>
                <el-table-column width="180">
                    <template slot="header" slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="修改原属性填写的内容，如果已有商品引用该属性，将会同步修改，请谨慎调整。" placement="top-start">
                            <el-button size="mini" icon="el-icon-question" circle></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-form-item v-if="valueTypeBoolean" label="是否自定义属性值" prop="valueType">
                <el-radio-group v-model="dataForm.valueType" :disabled="isAbled">
                    <el-radio :label="2">是</el-radio>
                    <el-radio :label="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <div style=" margin-top: 10px;" v-if="dataForm.valueType==1">
                <el-table :data="dataForm.productPropertyValues" :border="true" style="width: 542px">
                    <el-table-column v-if="false" type="index" prop="sortValue" width="55px">
                        <template slot-scope="scope">
                            <el-input v-model="scope.$index"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="属性值编码" width="180">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.code"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="属性值" width="180">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.name"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column width="180">
                        <template slot="header" slot-scope="scope">
                            <el-button size="mini" icon="el-icon-circle-plus" @click="addPropertyValue" circle></el-button>
                        </template>
                        <template slot-scope="scope">
                            <el-button @click="moveUp(scope.$index, scope.row)" type="text" size="small">上移</el-button>
                            <el-button type="text" @click="moveDown(scope.$index, scope.row)" size="small">下移</el-button>
                            <el-button type="text" size="small" @click="removePropertyValue(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:center">
            <el-button :size="size" @click.native="dialogVisible = false">
                {{$t("action.cancel")}}
            </el-button>
            <el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{ $t("action.submit") }}</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import CyTable from "@/views/Core/ProductTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import {
    format
} from "@/utils/datetime";
import {
    exportExcel
} from "@/utils/excel";
export default {
    components: {
        PopupTreeInput,
        CyTable,
        KtButton,
        TableColumnFilterDialog
    },
    data() {
        return {
            valueTypeBoolean: true,//是否自定义属性值字段是否展示，true展示，false不展示
            isAbled: false,
            isShowValue: true,
            tableData: [{}],
            size: "small",
            filters: {
                name: "",
                code: ""
            },
            columns: [],
            totalSize: 0,
            filterColumns: [],
            pageRequest: {
                pageNum: 1,
                pageSize: 10
            },
            pageResult: [],
            options: {},
            operation: false, // true:新增, false:编辑
            dialogVisible: false, // 新增编辑界面是否显示
            editLoading: false,
            dataFormRules: {
                code: [{
                        required: true,
                        message: "请输入属性编码",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 8,
                        message: "长度在 2 到 8 个字符",
                        trigger: "blur"
                    },
                    {
                        pattern: /^[^\u4e00-\u9fa5]+$/,
                        message: '属性编码不能包含汉字',
                        trigger: 'blur'
                    },
                    {
                        pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
                        message: '属性编码不能包含特殊字符',
                        trigger: 'blur'
                    },

                ],
                name: [{
                    required: true,
                    message: "请输入属性名称",
                    trigger: "blur"
                }]
            },
            // 新增编辑界面数据
            dataForm: {
                id: 0,
                name: "",
                code: "",
                valueType: 1,
                productPropertyValues: [{}]
            }
        };
    },
    methods: {
        // 获取分页数据
        findPage: function (params) {
            let this_ = this;
            if (params == undefined || params == null) {
                params = {
                    pageNum: this_.pageRequest.pageNum,
                    pageSize: this_.pageRequest.pageSize
                };
            }
            if (this_.filters == undefined || this_.filters == null) {
                this_.filters = {};
            }
            this_.filters.start = params.pageNum;
            this_.filters.limit = params.pageSize;
            this.utils.request.productNameProperty(this_.filters, function (res) {
                if (res.data.rows == null) {
                    res.data.rows = [];
                }
                this_.pageResult = res.data.rows;
                this_.totalSize = Number(res.data.total);
            });
        },
        // 批量删除
        handleDelete: function (data) {
            var ids = "";
            for (var i = 0; i < data.params.length; i++) {
                ids = ids + data.params[i].id + ",";
            }
            let param = {};
            param.ids = ids;
            this.utils.request.deleteProductNameProperty(param, this.deletInfoBack);
        },
        // 删除修改回调
        deletInfoBack: function (data) {
            if (data.code == "0000") {
                this.$message({
                    message: "操作成功",
                    type: "success"
                });
            } else {
                this.$message({
                    message: "操作失败, " + data.msg,
                    type: "error"
                });
            }
            this.findPage();
        },

        // 显示新增界面
        handleAdd: function () {
            this.isAbled = false;
            this.dialogVisible = true;
            this.operation = true;
            this.valueTypeBoolean = true;
            this.dataForm = {
                name: "",
                code: "",
                valueType: 1,
                productPropertyValues: [{}]
            };
        },
        // 显示编辑界面
        handleEdit: function (params) {
            this.isAbled = false;
            let this_ = this;
            this.dialogVisible = true;
            this.operation = false;
            this.valueTypeBoolean = false;
            this.dataForm.id = params.row.id;
            this.dataForm.code = params.row.code;
            this.dataForm.name = params.row.name;
            this.dataForm.valueType = 1;
            //根据属性名Id查询属性值
            let param = {};
            param.propertyId = params.row.id;
            this.utils.request.queryProductPropertyValue(param, function (res) {
                this_.dataForm.productPropertyValues = res.data;
            });
        },
        // 编辑
        submitForm: function () {
            let this_ = this;
            if (!this.dataForm.code) {
                this.$message({
                    message: "属性编码不能为空",
                    type: "error"
                });
                return;
            } else if(!/^[A-Za-z0-9]+$/.test(this.dataForm.code)){
              this.$message({
                message: "属性编码只能输入数字和英文字母",
                type: "error"
              });
              return;
            }
            if (!this.dataForm.name) {
                this.$message({
                    message: "属性名不能为空",
                    type: "error"
                });
                return;
            }
            let flag = true;
            let propertyValue = null;
            if (this.dataForm.valueType == 1) {
                $.each(this_.dataForm.productPropertyValues, function (index, val) {
                    if (val.name == "" || val.name == null) {
                        this_.$message({
                            message: "属性值不能为空",
                            type: "error"
                        });
                        flag = false;
                    }
                    if (propertyValue == val.name) {
                        this_.$message({
                            message: "存在相同的属性值",
                            type: "error"
                        });
                        flag = false;
                    }
                    propertyValue = val.name;
                    return flag;
                });
            } else {
                flag = true;
            }
            if (flag == true) {
                $.each(this_.dataForm.productPropertyValues, function (index, val) {
                    val.sortValue = index + 1;
                });
                this.$refs.dataForm.validate(valid => {
                    if (valid) {
                        this.$confirm("确认提交吗？", "提示", {}).then(() => {
                            let params = Object.assign({}, this.dataForm);
                            this.utils.request.editProductNameProperty(
                                params,
                                this.editInfoBack
                            );
                        });
                    }
                });
            }
        },

        // 新增修改回调
        editInfoBack: function (data) {
            if (data.code == "0000") {
                this.$message({
                    message: "操作成功",
                    type: "success"
                });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
                this.operation = false;
                this.editLoading = false;
            } else {
                this.$message({
                    message: "操作失败, " + data.msg,
                    type: "error"
                });
                this.editLoading = false;
            }
            this.findPage();
        },
        // 处理表格列过滤显示
        displayFilterColumnsDialog: function () {
            this.$refs.tableColumnFilterDialog.setDialogVisible(true);
        },
        // 处理表格列过滤显示
        handleFilterColumns: function (data) {
            this.filterColumns = data.filterColumns;
            this.$refs.tableColumnFilterDialog.setDialogVisible(false);
        },
        // 处理表格列过滤显示
        initColumns: function () {
            this.columns = [{
                    prop: "name",
                    label: "属性名称",
                    minWidth: 120
                },
                {
                    prop: "code",
                    label: "属性编码",
                    minWidth: 120
                },
                {
                    prop: "productPropertyValue",
                    label: "属性值",
                    minWidth: 120
                }
            ];
            var temp = [];
            $.each(this.columns, function (key, val) {
                temp.push(val);
            });
            this.filterColumns = temp;
        },
        resetForm(formName) {
            this.filters = {
                name: "",
                code: "",
                types: "",
                sortno: ""
            };
            this.findPage();
        },
        //删除属性值
        removePropertyValue: function (index, row) {
            let this_ = this;
            let propertyValue = {};
            //查询属性值是否关联类目
            propertyValue.attValueId = row.id;
            if (row.id != null && row.id != "") {
                this_.utils.request.queryByPropertyValueId(propertyValue, function (
                    res
                ) {
                    if (res.data.length != 0) {
                        this_.$message({
                            message: "属性值已在类目上使用",
                            type: "error"
                        });
                    } else {
                        var temp = [];
                        $.each(this_.dataForm.productPropertyValues, function (key, val) {
                            if (key == index) {} else {
                                temp.push(val);
                            }
                        });
                        this_.dataForm.productPropertyValues = temp;
                    }
                });
            } else {
                var temp = [];
                $.each(this_.dataForm.productPropertyValues, function (key, val) {
                    if (key == index) {} else {
                        temp.push(val);
                    }
                });
                this_.dataForm.productPropertyValues = temp;
            }
        },
        //添加属性值
        addPropertyValue: function (data) {
            let this_ = this;
            this_.dataForm.productPropertyValues.push({});
        },
        //上移属性值
        moveUp: function (index, row) {
            var this_ = this;
            console.log("上移", index, row);
            if (index > 0) {
                let upDate = this_.dataForm.productPropertyValues[index - 1];
                this_.dataForm.productPropertyValues.splice(index - 1, 1);
                this_.dataForm.productPropertyValues.splice(index, 0, upDate);
            } else {
                this.$message({
                    message: "已是第一条,不可上移",
                    type: "error"
                });
            }
        },
        //下移
        moveDown: function (index, row) {
            var this_ = this;
            if (index + 1 === this_.dataForm.productPropertyValues.length) {
                this.$message({
                    message: "已经是最后一条，不可下移",
                    type: "error"
                });
            } else {
                let downDate = this_.dataForm.productPropertyValues[index + 1];
                this_.dataForm.productPropertyValues.splice(index + 1, 1);
                this_.dataForm.productPropertyValues.splice(index, 0, downDate);
            }
        }
    },

    mounted() {
        this.initColumns();
    }
};
</script>

<style lang="scss" scoped>
/deep/ .el-form-item__error {
    margin-left: -50px;
}
</style>
